<template>
  <d2-container>
    <template slot="header">
      <el-form
        :inline="true"
        :model="queryForm"
        ref="queryForm"
        size="mini"
        style="margin-bottom: -18px;">

        <el-form-item label="状态" prop="type">
          <el-select
            v-model="queryForm.type"
            placeholder="状态选择"
            style="width: 100px;">
            <el-option label="用户名" value="username"/>
            <el-option label="email" value="email"/>
            <el-option label="姓名" value="name"/>
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="user">
          <el-input
            v-model="queryForm[queryForm.type]"
            placeholder="请输入"
            style="width: 200px;"/>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleFormSubmit">
            <d2-icon name="search"/>
            查询
          </el-button>
        </el-form-item>

      </el-form>
    </template>
<!--    @row-edit=""-->
    <template>
      <d2-crud
        ref="d2Crud"
        :columns="columns"
        :data="data"
        :loading="loading"
        :pagination="pagination"
        @pagination-current-change="paginationCurrentChange"
        add-title="新增用户"
        selection-row
        @selection-change="selectionChange"
        :rowHandle="rowHandle"
        @row-remove="handleRowRemove"
        :add-template="addTemplate"
        :add-rules="addRules"
        :form-options="formOptions"
        :edit-rules="editRules"
        @row-add="handleRowAdd"
        edit-title="编辑"
        :edit-template="editTemplate"
        @row-edit="handleRowEdit"
        @dialog-open="handleDialogOpen"
        @dialog-cancel="handleDialogCancel">
        <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
        <el-button size="mini" style="width: 100px; position: absolute; right: 20px; margin-bottom: 5px" slot="header" @click="deleteUser(selectedRow)">批量删除</el-button>
      </d2-crud>
    </template>
  </d2-container>
</template>

<script>
import api from '@/api'
let roleList = []
export default {
  name: 'user',
  data () {
    return {
      loading: true,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      queryForm: {
        type: 'username',
        username: '',
        email: '',
        name: ''
      },
      rowHandle: {
        width: 150,
        remove: {
          size: 'mini',
          fixed: 'left',
          confirm: true
        },
        columnHeader: '操作',
        edit: {
          text: '修改',
          size: 'mini',
          fixed: 'right'
        }
      },
      selectedRow: [],
      columns: [
        {
          title: '用户名',
          key: 'username',
          sortable: true
        },
        {
          title: 'E-mail',
          key: 'email',
          sortable: true
        },
        {
          title: '姓名',
          key: 'name',
          sortable: true
        },
        {
          title: '最后登录日期',
          key: 'loginDate',
          sortable: true
        },
        {
          title: '最后登录IP',
          key: 'loginIp',
          sortable: true
        },
        {
          title: '状态',
          key: 'isEnabled',
          sortable: true
        },
        // {
        //   title: '余额',
        //   key: 'balance',
        //   sortable: true
        // },
        {
          title: '创建日期',
          key: 'createDate',
          sortable: true
        }
      ],
      data: [],
      addRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
        password: [{ required: true, message: '请输入密码', trigger: 'change' }],
        rePassword: [{ required: true, message: '请输入密码', trigger: 'change' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }],
        department: [{ required: true, message: '请输入部门', trigger: 'change' }]
      },
      editRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }],
      },
      editTemplate: {
        username: {
          title: '用户名',
          value: '',
          component: {
            disabled: true
          }
        },
        email: {
          title: 'E-mail',
          value: ''
        },
        name: {
          title: '姓名',
          value: ''
        },
        // password: {
        //   title: '密码',
        //   value: ''
        // },
        // rePassword: {
        //   title: '确认密码',
        //   value: ''
        // },
        roleIds: {
          title: '角色',
          value: '',
          component: {
            name: 'el-select',
            multiple: true,
            options: []
          }
        },
        isEnabled: {
          title: '是否启用',
          value: true,
          component: {
            name: 'el-radio',
            options: [{
              value: true,
              label: '是'
            }, {
              value: false,
              label: '否'
            }]
          }
        },
        // balance: {
        //   title: '余额',
        //   value: ''
        // },
        telPhone: {
          title: '电话',
          value: ''
        },
        // overmoney: {
        //   title: '透支金额',
        //   value: ''
        // },
        department: {
          title: '部门',
          value: ''
        }
      },
      addTemplate: {
        username: {
          title: '用户名',
          value: ''
        },
        email: {
          title: 'E-mail',
          value: ''
        },
        name: {
          title: '姓名',
          value: ''
        },
        password: {
          title: '密码',
          value: ''
        },
        rePassword: {
          title: '确认密码',
          value: ''
        },
        roleIds: {
          title: '角色',
          value: '',
          component: {
            name: 'el-select',
            multiple: true,
            options: []
          }
        },
        isEnabled: {
          title: '是否启用',
          value: true,
          component: {
            name: 'el-radio',
            options: [{
              value: true,
              label: '是'
            }, {
              value: false,
              label: '否'
            }]
          }
        },
        // balance: {
        //   title: '余额',
        //   value: ''
        // },
        telPhone: {
          title: '电话',
          value: ''
        },
        // overmoney: {
        //   title: '透支金额',
        //   value: ''
        // },
        department: {
          title: '部门',
          value: ''
        }
      },
      formOptions: {
        labelWidth: '120px',
        labelPosition: 'left',
        saveLoading: false
      }
    }
  },
  watch: {
    'queryForm.type' (val, oVal) {
      if (!oVal) return
      for (const key in this.queryForm) {
        if (key !== 'type') {
          this.queryForm[key] = ''
        }
      }
    }
  },
  mounted () {
    this.getRoleList()
    this.getUserList()
  },
  methods: {
    handleDialogOpen ({ mode, row, index }) {
      if (mode === 'edit') {
        this.$api.GET_USER(row.id).then(res => {
          this.$refs.d2Crud.setFormData(res)
        })
      }
    },
    // 获取角色列表
    async getRoleList () {
      const res = await api.admin_role_getList()
      if (res) {
        roleList = res.map(r => {
          return {
            value: r.id,
            label: r.name
          }
        })
        this.addTemplate.roleIds.component.options = roleList
        this.editTemplate.roleIds.component.options = roleList
      }
    },
    paginationCurrentChange (currentPage) {
      this.pagination.currentPage = currentPage
      this.getUserList()
    },
    // 获取用户列表
    async getUserList () {
      const res = await api.GET_USER_LIST({
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        ...this.queryForm
      })
      if (res && res.columns) {
        const { data } = res
        this.data = data
        this.pagination.total = res.total
        this.loading = false
        console.log(this.data);
      }
      return res
    },
    async addUser (params, done) {
      this.$api.ADD_USER(params).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        this.getUserList();
        done();
        this.formOptions.saveLoading = false
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        });
        this.formOptions.saveLoading = false
      }).finally(() => {
        this.formOptions.saveLoading = false
      })
    },
    async updateUser (params, done) {
      this.$api.UPDATE_USER(params).then(res => {
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.getUserList();
        done();
        this.formOptions.saveLoading = false
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        });
        this.formOptions.saveLoading = false
      }).finally(() => {
        this.formOptions.saveLoading = false
      })
    },
    selectionChange (data) {
      this.selectedRow = data.map(d => d.id)
    },
    // 删除用户
    async deleteUser (id) {
      if (!id || !id.length) return
      const params = id
      this.$api.DELETE_USER(params).then(res => {
        this.pagination.currentPage = 1
        this.getUserList().then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        })
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
      })
    },
    handleRowRemove ({ index, row }, done) {
      this.deleteUser([row.id])
    },
    handleFormSubmit () {
      this.getUserList()
    },
    addRow () {
      this.$refs.d2Crud.showDialog({
        mode: 'add'
      })
    },
    handleRowAdd (row, done) {
      const params = JSON.parse(JSON.stringify(row))
      this.pagination.currentPage = 1
      this.formOptions.saveLoading = true
      this.addUser(params, done)
    },
    handleRowEdit ({ index, row }, done) {
      const params = JSON.parse(JSON.stringify(row))
      // this.pagination.currentPage = 1
      this.formOptions.saveLoading = true
      this.updateUser(params, done)
    },
    handleDialogCancel (done) {
      this.$message({
        message: '取消保存',
        type: 'warning'
      })
      done()
    }
  }
}
</script>
